﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;

namespace QLHPHP
{   
    /// <summary>
    /// Class ket noi csdl thuc hien cac truy van
    /// </summary>
    public static class DataAccess
    {
        static DataAccess()
        { 
        
        }

        /// <summary>
        /// Thu hien truy van select
        /// </summary>
        /// <param name="comm"></param>
        /// <returns></returns>
        public static DataTable ExecuteSelectCommand(DbCommand comm)
        {
            DataTable table;
            try
            {
                comm.Connection.Open();
                DbDataReader reader = comm.ExecuteReader();
                table = new DataTable();
                table.Load(reader);
                return table;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                comm.Connection.Close(); 
            }
        }
        /// <summary>
        /// Tao ra 1 doi tuong SQLCommand
        /// </summary>
        /// <returns></returns>
        public static DbCommand CreateCommand()
        {
            //dung he quan tri csdl la Sql thi thiet lap the nay
            //he quan tri khac thiet lap dataProviderName tuong ung
            string dataProviderName = "System.Data.SqlClient";

            //lay chuoi ket noi database tu static class config
            string connectionString = Config.ConnectionString;
            //string connectionString = Program.DatabaseFilesCollection.ToString();

            //tao factory 
            DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = connectionString;
            DbCommand comm = connection.CreateCommand();
            comm.CommandType = CommandType.StoredProcedure;

            //tra ve doi tuong comm
            return comm;  
        }

        /// <summary>
        /// Thuc thi cac ham insert, update, delete
        /// </summary>
        /// <param name="comm"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(DbCommand comm)
        {
            int affectedRows = -1;
            try
            {
                comm.Connection.Open();
                affectedRows = comm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw;
                //MessageBox.Show(ex.ToString(), "Lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                comm.Connection.Close();
            }

            return affectedRows;
        }
    }
}
